const express = require("express");
const router = express.Router();
const process = require("process");
const { spawnSync } = require("child_process");
const path = require("path");
const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");

router.get("/", function (req, res, next) {
  res.redirect("/static/index.html");
});

router.get("/local-ip", (req, res, next) => {
  const interfaces = require("os").networkInterfaces();
  for (let devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return res.json({ ip: alias.address });
      }
    }
  }
});

router.get("/cut-image", (req, res) => {
  const cutProcess = spawnSync(
    "python",
    [
      "crop.py",
      "--traj",
      req.app.locals.taskInfo.traj,
      "--scene",
      req.app.locals.taskInfo.scene + ".jpg",
    ],
    { cwd: path.join(process.cwd(), "app") }
  );
  if (cutProcess.status !== 0) {
    console.log(cutProcess.stderr.toString());
    return res.json({
      code: 1,
      message: "裁减图片失败",
    });
  }
  return res.json({ code: 0, message: "裁减图片成功" });
});

router.get("/get-image/:name", (req, res) => {
  const imgPath = path.join(
    process.cwd(),
    "app",
    "output_images",
    req.params.name
  );
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.write(chunk);
  });
  stream.on("end", () => {
    res.status(200);
    res.end();
  });
});

router.post("/tran-image", async (req, res) => {
  try {
    await axios.get(`http://${req.body.ip}:${req.body.port}/api/init`);
    const fileNodes = fs.readdirSync(
      path.join(process.cwd(), "app", "output_images")
    );
    for (let i = 0; i < fileNodes.length; i++) {
      const formData = new FormData();
      const imgPath = path.join(
        process.cwd(),
        "app",
        "output_images",
        fileNodes[i]
      );
      formData.append("image", fs.createReadStream(imgPath));
      // 发送图片
      await axios.post(
        `http://${req.body.ip}:${req.body.port}/api/upload`,
        formData,
        formData.getHeaders()
      );
      req.app.locals.ws.send(`tran ${i + 1}`);
    }
    req.app.locals.ws.send("tran done");

    await axios.post(
      `http://${req.body.ip}:${req.body.port}/api/run`,
      req.app.locals.taskInfo
    );
    return res.json({ code: 0, message: "文件传输结束" });
  } catch (err) {
    return res.json({ code: 1, message: "下位机激活失败" });
  }
});

module.exports = router;
